package com.example.day_day_up.service.impl;

import com.example.day_day_up.entity.vo.ViewMaterialVO;
import com.example.day_day_up.entity.vo.WebMaterialVO;
import com.example.day_day_up.entity.po.Material;
import com.example.day_day_up.entity.po.MaterialStatus;
import com.example.day_day_up.mappers.MaterialMapper;
import com.example.day_day_up.mappers.MaterialStatusMapper;
import com.example.day_day_up.service.MaterialService;
import com.example.day_day_up.utils.DateUtils;

import java.util.ArrayList;
import java.util.List;

public class MaterialServiceImpl implements MaterialService {
    private final MaterialMapper materialMapper;
    private final MaterialStatusMapper materialStatusMapper;

    public MaterialServiceImpl(MaterialMapper materialMapper, MaterialStatusMapper materialStatusMapper) {
        this.materialMapper = materialMapper;
        this.materialStatusMapper = materialStatusMapper;
    }


    @Override
    public ViewMaterialVO selectMaterialByID(String id) {
        Material material = materialMapper.selectByID(id);
        ViewMaterialVO materialDTO = new ViewMaterialVO();
        materialDTO.setId(material.getId());
        materialDTO.setName(material.getName());
        materialDTO.setType(material.getType());
        materialDTO.setStoreName(material.getStoreName());
        materialDTO.setCourseId(material.getCourseId());
        return materialDTO;
    }

    @Override
    public List<WebMaterialVO> selectMaterialByCIDAndUID(String cId, String uId) {
        List<Material> materials = materialMapper.selectByCID(cId);
        List<WebMaterialVO> materialDTOS = new ArrayList<>();
        for (Material material : materials) {
            WebMaterialVO materialDTO = new WebMaterialVO();
            materialDTO.setId(material.getId());
            materialDTO.setName(material.getName());
            materialDTO.setStoreName(material.getStoreName());
            materialDTO.setType(material.getType());
            materialDTO.setCreatorName(material.getCreatorName());
            // 将材料创建时间转化成字符串
            materialDTO.setCreateTime(DateUtils.transToStr(material.getCreateTime()));
            // 根据材料编号(m_id)和用户编号(u_id)查找材料学习状态
            Boolean status = getStatus(material.getId(), uId);
            materialDTO.setStatus(status);
            materialDTOS.add(materialDTO);
        }
        return materialDTOS;
    }

    private Boolean getStatus(String mId, String uId) {
        MaterialStatus status = materialStatusMapper.selectByMIDAndUID(mId, uId);
        // 第一次为资料设置状态 ， 即未学习
        if (null == status) {
            status = new MaterialStatus(mId, uId, false);
            materialStatusMapper.insert(status);

            return false;
        }
        // 不为空则返回资料的状态
        return status.getStatus();
    }
}
